const moment = require("moment");
const McMeeting = require('./db/mc_meeting')

const path = require('path');
const clouddb = require('@hw-agconnect/database-server/dist/index.js')
import { AGCClient, CredentialParser } from "@agconnect/common-server"

// 加载凭证文件
let client_name = "./db/agc-apiclient-mlc.json";
let client_path = path.join(__dirname, client_name);
let credential = CredentialParser.toCredential(client_path);
AGCClient.initialize(credential, "clientDW");
const agcClient = AGCClient.getInstance("clientDW");
clouddb.AGConnectCloudDB.initialize(agcClient);
const agconnectCloudDB = clouddb.AGConnectCloudDB.getInstance(agcClient);

//云数据库区块
const zoneName = 'mlc01';
const cloudDBZoneConfig = new clouddb.CloudDBZoneConfig(zoneName);
const mCloudDBZone = agconnectCloudDB.openCloudDBZone(cloudDBZoneConfig);

let myHandler = async function (event, context, callback, logger) {
  // 获取参数
  const { meetingId, status, noteUrl, audioUrl, docsUrl, userId, abstract, startTime, endTime } = event.body ? JSON.parse(event.body) : event
  // 打印获取参数
  logger.info("meetingId:", meetingId);
  logger.info("status:", status);
  logger.info("noteUrl:", noteUrl);
  logger.info("audioUrl:", audioUrl);
  logger.info("docsUrl:", docsUrl);
  logger.info("startTime:", startTime);
  logger.info("endTime:", endTime);

  // 构建数据体
  const meeting = new McMeeting.mc_meeting()
  meeting.setId(meetingId)
  const operator = clouddb.CloudDBZoneObjectOperator.build(meeting);

  const meetingJson = {
    status,
    noteUrl,
    audioUrl,
    docsUrl,
    abstract,
    startTime: startTime && moment(startTime, "YYYY/MM/DD HH:mm:ss").toDate(),
    endTime: endTime && moment(endTime, "YYYY/MM/DD HH:mm:ss").toDate(),
    updateTime: new Date()
  }

  for (const key in meetingJson) {
    if (![undefined, null].includes(meetingJson[key])) {
      operator.update(key, meetingJson[key]);
    }
  }

  try {
    const updateNum = await mCloudDBZone.executeUpdate(operator)
    logger.info("updateNum=>", updateNum)
  } catch (error) {
    logger.warn('updateError=>', error)
  }

  let res = new context.HTTPResponse({
    code: 200,
    msg: '成功',
    data: meetingJson
  }, {
    "faas-content-type": "json"
  }, "application/json", "200");


  callback(res);
};

export { myHandler };